﻿@inject IHttpService _httpService
@inject IPopupService PopupService
@inject NavigationManager NavigationManager

<MDCard>
    <DataTableCard TModel="WinnerOverviewModel" Headers="_headers" DataSource="Model" Title="@($"{_name}列表")" ShowAddButton="false" @ref="dataTableCard"
                   Predicate="s => dataTableCard==null ||string.IsNullOrWhiteSpace(dataTableCard._search) || (s.AwardName!=null&&s.AwardName.Contains(dataTableCard._search))|| (s.RealName!=null&&s.RealName.Contains(dataTableCard._search))|| (s.UserName!=null&&s.UserName.Contains(dataTableCard._search))|| (s.Email!=null&&s.Email.Contains(dataTableCard._search))">
        <ItemColContent>
            @if (context.Header.Value == "actions")
            {
                <div style="width: 140px;">
                    @if (!(context.Item.AwardType == LotteryAwardType.RealThing && string.IsNullOrWhiteSpace(context.Item.TrackingNumber)) && context.Item.AwardType != LotteryAwardType.Integral)
                    {
                        <MIcon Color="success"
                               Class="mr-2"
                               OnClick="()=>EditItem(context.Item)">@IconType.Edit.ToIconString()</MIcon>
                    }
                    @if (context.Item.AwardType == LotteryAwardType.RealThing && string.IsNullOrWhiteSpace(context.Item.TrackingNumber))
                    {
                        <MIcon Color="error"
                               Class="mr-2"
                               OnClick="()=>EditItem(context.Item)">@IconType.Execute.ToIconString()</MIcon>
                    }
                </div>
            }
            else if (context.Header.Value == nameof(WinnerOverviewModel.Id))
            {
                <CnGalWebSite.Shared.MasaComponent.PC.EditRecords.UserCenter.ReviewEditRecords.UserChip Id="@context.Item.Id" Name="@context.Item.UserName" />
            }
            else if (context.Header.Value == nameof(WinnerOverviewModel.AwardType))
            {
                <CnGalWebSite.Shared.MasaComponent.PC.Admin.Lotteries.AwardChip Type="@context.Item.AwardType" Name="@context.Item.AwardName" />
            }
            else
            {
                @context.Value
            }
        </ItemColContent>
    </DataTableCard>

</MDCard>

<MDialog @bind-Value="Dialog"
         Width="600">
    <MDCard>
        <MCardTitle Class="text-h5">
            编辑奖品
        </MCardTitle>
        <MCardText>
            输入完毕后点击保存即可生效
        </MCardText>

        <MCardText>
            @if (currentWinner.AwardType == LotteryAwardType.ActivationCode)
            {
                <MTextField @bind-Value="tempStr" Label="激活码"  />

            }
            else
            {
                <MTextField @bind-Value="tempStr" Label="快递单号"  />
            }
        </MCardText>
        <MCardActions Class="pb-6 pe-6 ps-6 pt-6">
            <MSpacer></MSpacer>
            <CnGalWebSite.Components.Buttons.MasaButton Text="保存" IsAsync="true" OnClick="OnSubmit" Icon="mdi-check" Color="success" TextStyle />
        </MCardActions>
    </MDCard>
</MDialog>

 @code {
    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }
    [Parameter]
    public long Id { get; set; }


    bool Dialog { get; set; }

    WinnerOverviewModel currentWinner { get; set; } = new WinnerOverviewModel();
    string tempStr;

    public List<WinnerOverviewModel> Model { get; set; } = new List<WinnerOverviewModel>();

    private string _name = "中奖用户";

    private List<DataTableHeader<WinnerOverviewModel>> _headers = new List<DataTableHeader<WinnerOverviewModel>>
{
          new ()
          {
            Text= "号码",
            Align= DataTableHeaderAlign.Start,
            Value= nameof(WinnerOverviewModel.Number)
          },
          new (){ Text= "用户名", Value= nameof(WinnerOverviewModel.Id)},
          new (){ Text= "电子邮箱", Value= nameof(WinnerOverviewModel.Email)},
          new (){ Text= "类型", Value= nameof(WinnerOverviewModel.AwardType)},
          new (){ Text= "激活码", Value= nameof(WinnerOverviewModel.ActivationCode)},
          new (){ Text= "快递单号", Value= nameof(WinnerOverviewModel.TrackingNumber)},
          new (){ Text= "真实姓名", Value= nameof(WinnerOverviewModel.RealName)},
          new (){ Text= "地址", Value= nameof(WinnerOverviewModel.Address)},
          new (){ Text= "电话号码", Value= nameof(WinnerOverviewModel.Phone)},
          new (){ Text= "操作", Value= "actions",Sortable=false }
    };

    DataTableCard<WinnerOverviewModel> dataTableCard;


    protected override async Task OnInitializedAsync()
    {
        try
        {
            Model.Clear();
            Model.AddRange(await _httpService.GetAsync<List<WinnerOverviewModel>>("api/lotteries/GetWinnerDatas/" + Id));
            dataTableCard?.GetDataFromApi();
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "无法获取中奖用户列表");
        }
    }

    public void EditItem(WinnerOverviewModel model)
    {
        currentWinner = model;
        if (currentWinner.AwardType == LotteryAwardType.ActivationCode)
        {
            tempStr = currentWinner.ActivationCode;
        }
        else
        {
            tempStr = currentWinner.TrackingNumber;
        }
        Dialog = true;
        StateHasChanged();
    }

    public async Task OnSubmit()
    {
        try
        {
            var obj = await _httpService.PostAsync<EditUserPrizeModel, Result>("api/lotteries/EditUserPrize", new EditUserPrizeModel
            {
                Context = tempStr,
                LotteryAwardId = currentWinner.AwardId,
                UserId = currentWinner.Id
            });
            if (obj.Successful)
            {
                if (currentWinner.AwardType == LotteryAwardType.ActivationCode)
                {
                    currentWinner.ActivationCode = tempStr;
                }
                else
                {
                    currentWinner.TrackingNumber = tempStr;
                }
                Dialog = false;
                StateHasChanged();
                await PopupService.ToastAsync("编辑奖品成功", AlertTypes.Success);
            }
            else
            {
                await PopupService.ToastAsync("编辑奖品失败", AlertTypes.Error);
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "编辑用户奖品失败");
        }
    }
}
